package com.longtop.framework.sys.org.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.longtop.framework.base.BaseService;
import com.longtop.framework.common.CacheUpdate;
import com.longtop.framework.common.Constant;
import com.longtop.framework.common.QueryConditions;
import com.longtop.framework.common.QueryResult;
import com.longtop.framework.security.BaseCheckedException;
import com.longtop.framework.security.SessionObject;
import com.longtop.framework.sys.org.model.TSysOrg;
import com.longtop.framework.util.StringUtil;
import com.longtop.intelliweb.action.IInitContext;
import com.longtop.intelliweb.common.Constants;
import com.longtop.intelliweb.view.DataTree;
import com.longtop.intelliweb.view.Dataset;
import com.longtop.intelliweb.view.Record;

/**
 * 系统管理-机构service
 * 
 * @author SJH
 */
public class OrgService extends BaseService {

	public static final String BEAN_ID = "orgService";

	/**
	 * 提交保存
	 * 
	 * @param changeMap
	 * @return
	 * @throws BaseCheckedException
	 */
	public Integer[] saveOrg(Map changeMap) throws BaseCheckedException {

		// 插入成功的记录数、更新成功的记录数、删除成功的记录数
		int insertCount = 0;
		int updateCount = 0;
		int deleteCount = 0;

		// 删除主键列表、更新bean的列表、新增bean的列表
		List insertBeanList = (ArrayList) changeMap.get(Constant.INSERT_BEAN_LIST);
		List updateBeanList = (ArrayList) changeMap.get(Constant.UPDATE_BEAN_LIST);
		String idList = (String) changeMap.get(Constant.ID_LIST);

		TSysOrg tSysOrg;
		Iterator iterator;

		// 批量插入记录
		if (insertBeanList.size() > 0) {
			iterator = insertBeanList.iterator();
			while (iterator.hasNext()) {
				tSysOrg = (TSysOrg) iterator.next();

				// 校验id是否重复。
				if (isExistOrgId(tSysOrg.getOrgId()))
					throw new BaseCheckedException("", "保存失败,机构id【" + tSysOrg.getOrgId() + "】已经存在!");

				// 计算机构级次，机构级次码
				if (StringUtils.isEmpty(tSysOrg.getParentOrgId())) {
					tSysOrg.setOrgLevel(1);
					tSysOrg.setOrgLevelCode(tSysOrg.getOrgId());
				} else {
					TSysOrg parentSysOrg = this.get(TSysOrg.class, tSysOrg.getParentOrgId()); // 父节点
					tSysOrg.setOrgLevel(parentSysOrg.getOrgLevel() + 1);
					tSysOrg.setOrgLevelCode(parentSysOrg.getOrgLevelCode() + "|" + tSysOrg.getOrgId());
				}

				super.save(tSysOrg);
				insertCount++;
			}
		}

		// 批量更新记录
		if (updateBeanList.size() > 0) {
			iterator = updateBeanList.iterator();
			while (iterator.hasNext()) {
				tSysOrg = (TSysOrg) iterator.next();

				// 计算机构级次，机构级次码
				if (StringUtils.isEmpty(tSysOrg.getParentOrgId())) {
					tSysOrg.setOrgLevel(1);
					tSysOrg.setOrgLevelCode(tSysOrg.getOrgId());
				} else {
					TSysOrg parentSysOrg = this.get(TSysOrg.class, tSysOrg.getParentOrgId()); // 父节点
					tSysOrg.setOrgLevel(parentSysOrg.getOrgLevel() + 1);
					tSysOrg.setOrgLevelCode(parentSysOrg.getOrgLevelCode() + "|" + tSysOrg.getOrgId());
				}

				super.update(tSysOrg);
				updateCount++;
			}
		}

		// 批量删除记录
		if (idList.length() > 0) {
			String sql = "delete from TSysOrg where orgId in(" + idList + ")";
			deleteCount = super.batchUpdate(sql);
		}

		// 更新緩存：
		getHibernateTemplate().flush();
		CacheUpdate.getCacheUpdate().updateOrgMap();
		CacheUpdate.getCacheUpdate().updateAllSubOrgMap();

		return new Integer[] { new Integer(insertCount), new Integer(updateCount), new Integer(deleteCount) };
	}

	/**
	 * 验证此机构Id 是否存在
	 * 
	 * @param menuId
	 * @return
	 */
	private boolean isExistOrgId(String orgId) {
		boolean flag = false;
		List list = this.queryAll("from TSysOrg where orgId='" + orgId + "'");
		if (list.size() > 0)
			flag = true;
		return flag;
	}

	/**
	 * 读取机构
	 * 
	 * @param queryConditions
	 * @param filter
	 * @return
	 */
	public QueryResult loadOrg(QueryConditions queryConditions, String filter) {
		queryConditions.setOrderBy("sortNo asc");// 排序
		return super.loadByConditions(queryConditions, TSysOrg.class, filter);
	}

	/**
	 * 删除机构
	 * 
	 * @param id
	 *            要删除的机构ID
	 * @param sessionObject
	 *            session对象
	 */
	public void deleteOrg(String id, SessionObject sessionObject) {

		// 删除机构及其对应的功能
		super.delete(TSysOrg.class, id);
	}

	/**
	 * 读取 机构org 信息 ,并根据 机构id 组织成一个 Map， 此方法供 系统启动时候的Listener调用。
	 * 
	 * @return 机构信息的Map
	 * 
	 * @author 胡砥峰
	 */
	public Map<String, TSysOrg> getOrgMap() {
		Map orgMap = new HashMap();
		List list = this.queryAll("from TSysOrg order by sortNo asc");
		TSysOrg tSysOrg;
		Iterator it = list.iterator();
		while (it.hasNext()) {
			tSysOrg = (TSysOrg) it.next();
			orgMap.put(tSysOrg.getOrgId(), tSysOrg);
		}

		return orgMap;
	}

	/**
	 * 读取 机构org 信息 ,返回一个list， 此方法供 系统启动时候的Listener调用。
	 * 
	 * @return 机构信息的list
	 * 
	 * @author 胡砥峰
	 */
	public List<TSysOrg> getOrgList() {
		return this.queryAll("from TSysOrg order by sortNo asc");
	}

	/**
	 * 获取不同用户权限的机构树数据
	 * 
	 * @param context
	 */
	public void getOrgTreeAuth(Dataset orgDataset, IInitContext context) {

		SessionObject sessionObject = (SessionObject) context.getRequest().getSession().getAttribute(Constant.SESSION_OBJECT);
		Map<String, Object> queryMap = new HashMap<String, Object>();

		// 是否需要设置权限：（从页面参数传入）
		String isFilter = StringUtil.getString(context.getRequest().getParameter("isFilter"));
		String filter = "1=1";
		if (!"false".equals(isFilter)) {
			filter = sessionObject.getGrantFilterSql("T_SYS_ORG", "O", "ORG_ID", null);
		}
		System.out.println("【TEST数据权限】" + filter);
		queryMap.put("grantFilterSql", filter);

		this.queryForPageByIbatis("sysOrgSql.selectOrgToDropDown", null, queryMap, orgDataset, false);

		if (!"false".equals(isFilter)) {
			// 设置机构树的根节点的父节点ID为NULL，这样才能完整显示机构树：
			String parentOrgId = "";
			if (filter.indexOf("like") != -1) {
				parentOrgId = filter.substring(filter.lastIndexOf('%') - 5, filter.lastIndexOf('%'));
			} else if (filter.indexOf("=") != -1 && filter.indexOf("(") != -1) {
				parentOrgId = filter.substring(filter.lastIndexOf("'") - 5, filter.lastIndexOf("'"));
			}
			System.out.println(parentOrgId);
			Record record = orgDataset.location(new String[] { "orgId" }, new String[] { parentOrgId }, new String[] { Constants.COMPARE_GREATER_EQUAL });
			if (record != null) {
				record.setValue("parentOrgId", "");
			}

			// 若查询记录只有1条，则不延长加载
			if (orgDataset.getRecordList().size() <= 1) {
				DataTree dataTree = (DataTree) context.getControl("DataTree_Org");
				if (dataTree != null) {
					dataTree.setLazyLoading(false);
				}
			}
		}

	}

	/**
	 * 获取本机构所属一级机构
	 * 
	 * @param sessionObject
	 * @return
	 */
	public String getOrgIdFromLevelOne(SessionObject sessionObject) {
		String orgId = sessionObject.getOrgId();
		if (sessionObject.getOrgLevel().equals("3") || (orgId.substring(0, 2).equals("00") && !orgId.equals("00000"))) {
			orgId = sessionObject.getParentOrgId();
		}
		return orgId;
	}
}